package com.niit.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button write = findViewById(R.id.btnWrite);
        Button read = findViewById(R.id.btnRead);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText name = findViewById(R.id.name);
                EditText age = findViewById(R.id.age);
                prefs = getSharedPreferences("myInfo", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("name",name.getText().toString());
                editor.putInt("age",Integer.parseInt(age.getText().toString()));
                editor.commit();
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences shared = getSharedPreferences("myInfo",Context.MODE_PRIVATE);
                String getName = shared.getString("name","");
                int getAge = shared.getInt("age",0);

                Toast.makeText(MainActivity.this,"您的姓名为："+getName+",您的年龄为："+getAge,Toast.LENGTH_LONG).show();
            }
        });
    }
}